package com.lemon.smartsafety.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.widget.FrameLayout;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.BuildConfig;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.data.app.DataUtil;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerClickEventForMain;
import com.lemon.smartsafety.entity.event.main.drawer.DrawerRefreshEvent;
import com.lemon.smartsafety.entity.event.user.UpDateUserInfoEvent;
import com.lemon.smartsafety.entity.event.user.UserSetRefreshEvent;
import com.lemon.smartsafety.entity.notice.NoticeInfoVo;
import com.lemon.smartsafety.entity.version.VersionVo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.UrlInfo;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.address.ReceiverContentMode;
import com.lemon.smartsafety.result.user.UserInfoMode;
import com.lemon.smartsafetynew.ui.activity.base.BaseActivity;
import com.lemon.smartsafety.ui.activity.notice.NoticeDetailActivity;
import com.lemon.smartsafety.ui.fragment.DrawerFragment;
import com.lemon.smartsafety.ui.fragment.MainFragment;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.update.UpdateManager;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafety.utils.common.DoubleClickExitHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.location.LocationBaiDuUtils;
import com.lemon.safecloud.greendao.PlayView;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushManager;
//import com.tencent.bugly.beta.Beta;
//import com.tencent.bugly.beta.UpgradeInfo;
import com.thefinestartist.finestwebview.FinestWebView;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Cooliean on 16/1/15.
 */
public class    MainActivity extends BaseActivity {
    private LoggerHelper loggerHelper = new LoggerHelper(MainActivity.class);
    private DrawerFragment mNavigationFragment;
    private BaseFragment mCurrentFragment;
    DoubleClickExitHelper mDoubleClickExit;

    private int mCurrentDrawId = R.string.draw_home;


    private int mOldColumnPosition = -1;


    private Map<String, BaseFragment> mBaseFragmentMap = new HashMap<>();
    private Map<Integer, String> mDrawerIdMap = new HashMap<>();
    private LocationBaiDuUtils locationBaiDuUtils;


    @Override
    protected void initViews() {
        getWindow().setBackgroundDrawable(null);
        mDoubleClickExit = new DoubleClickExitHelper(this);


        mNavigationFragment = (DrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mNavigationFragment.setUp((FrameLayout) findViewById(R.id.main_content), R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.main_drawer));
        initDrawerMap();
        mCurrentFragment = getFragment(mDrawerIdMap.get(R.string.draw_home));
        transactionSupportFragment(mCurrentFragment);

        if (BuildConfig.DEBUG) {
            AppUtils.testScreen(this);
        }


        if (BuildConfig.FLAVOR.equals("bugly_beta") && !BuildConfig.DEBUG) {
            /***** 检查更新 *****/
            //Beta.checkUpgrade();
            //loadUpgradeInfo();
        }

        AppService.getBus().post(new UpDateUserInfoEvent());

   /*     try {
            locationBaiDuUtils = new LocationBaiDuUtils(MainActivity.this);
            locationBaiDuUtils.setCallBackListen(new LocationBaiDuUtils.CallBackInterface() {
                @Override
                public void callBackFunction(boolean Success,BDLocation location) {
                    LogUtils.LOGE("初始化本地时时地理位置成功");
                }
            });
            locationBaiDuUtils.test();
            locationBaiDuUtils.initLocation();

        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    @Override
    protected void getBundleArgs() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }


    private BaseFragment getFragment(String fragmentName) {
        BaseFragment baseFragment = mBaseFragmentMap.get(fragmentName);
        if (baseFragment == null) {
            try {
                baseFragment = (BaseFragment) Class.forName(fragmentName).newInstance();
            } catch (Exception e) {
                e.printStackTrace();
                baseFragment = MainFragment.newInstance();
            }
            mBaseFragmentMap.put(fragmentName, baseFragment);
        }
        return baseFragment;
    }

    @Subscribe
    public void onEventMainThread(DrawerClickEventForMain drawerClickEvent) {

        if (Constants.Result.ERROR.equals(drawerClickEvent.getEventResult()) || drawerClickEvent.getDrawId() == mCurrentDrawId) {
            return;
        }
        mCurrentDrawId = drawerClickEvent.getDrawId();
        if (mCurrentDrawId == R.string.draw_app && !mSharedPreferencesHelper.isLogin()) {
            UIHelper.showLoginActivity(MainActivity.this);
            return;
        }


        if (drawerClickEvent.getColumnPosition() != -1 || drawerClickEvent.getDrawId() == R.string.draw_news) {//新闻部分的特殊处理

            DrawerRefreshEvent refreshEvent = new DrawerRefreshEvent();//刷新左边的菜单
            refreshEvent.setPosition(drawerClickEvent.getDrawPosition());
            AppService.getBus().post(refreshEvent);


            mOldColumnPosition = drawerClickEvent.getColumnPosition();// 这里线不考虑缓存了。都New
            String fragmentClassName = mDrawerIdMap.get(mCurrentDrawId);
            BaseFragment baseFragment = null;
            try {
                baseFragment = (BaseFragment) Class.forName(fragmentClassName).newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (baseFragment != null) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(BundleKey.NEWS_COLUMN_POSITION, mOldColumnPosition);
                    baseFragment.setArguments(bundle);
                    mBaseFragmentMap.put(fragmentClassName, baseFragment);
                    mCurrentFragment = baseFragment;
                }
            }

        } else {
            mCurrentFragment = getFragment(mDrawerIdMap.get(mCurrentDrawId));
        }

        transactionSupportFragment(mCurrentFragment);
    }


    private void initDrawerMap() {
        mDrawerIdMap = DataUtil.getListForMainActivity();
    }


    private void transactionSupportFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content, fragment).commit();
    }

    /**
     * 监听返回--是否退出程序
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mNavigationFragment.isDrawerOpen()) {
                mNavigationFragment.closeDrawer();
                return false;
            } else {
                // 是否退出应用
                return mDoubleClickExit.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    //delete by Andrew.yin 2017/9/24 begin
//    private void loadUpgradeInfo() {
//        /***** 获取升级信息 *****/
//        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
//
//        if (upgradeInfo == null) {
//            return;
//        }
//
//        StringBuilder info = new StringBuilder();
//        info.append("id: ").append(upgradeInfo.id).append("\n");
//        info.append("标题: ").append(upgradeInfo.title).append("\n");
//        info.append("升级说明: ").append(upgradeInfo.newFeature).append("\n");
//        info.append("versionCode: ").append(upgradeInfo.versionCode).append("\n");
//        info.append("versionName: ").append(upgradeInfo.versionName).append("\n");
//        info.append("发布时间: ").append(upgradeInfo.publishTime).append("\n");
//        info.append("安装包Md5: ").append(upgradeInfo.apkMd5).append("\n");
//        info.append("安装包下载地址: ").append(upgradeInfo.apkUrl).append("\n");
//        info.append("安装包大小: ").append(upgradeInfo.fileSize).append("\n");
//        info.append("弹窗间隔（ms）: ").append(upgradeInfo.popInterval).append("\n");
//        info.append("弹窗次数: ").append(upgradeInfo.popTimes).append("\n");
//        info.append("发布类型（0:测试 1:正式）: ").append(upgradeInfo.publishType).append("\n");
//        info.append("弹窗类型（1:建议 2:强制 3:手工）: ").append(upgradeInfo.upgradeType);
//
//        loggerHelper.w(info.toString());
//    }
    //delete by Andrew.yin 2017/9/24 begin


    @Override
    protected void onResume() {
        super.onResume();

        XGPushClickedResult click = XGPushManager.onActivityStarted(MainActivity.this);
        Log.e("推送过来的TPush:", "onResumeXGPushClickedResult:" + click);
        if (click != null) { // 判断是否来自信鸽的打开方式
            if (!CommonUtil.strIsEmpty(click.getCustomContent())) {
                try {
                    ReceiverContentMode receiverContentMode = new Gson().fromJson(click.getCustomContent(), ReceiverContentMode.class);
                    if (CommonUtil.objIsEmpty(receiverContentMode)) {
                        return;
                    }

                    switch (receiverContentMode.getCode()) {
                        //新闻公告
                        case 1000:
                            PlayView playView = new Gson().fromJson(receiverContentMode.getObj(), PlayView.class);
                            if (!CommonUtil.objIsEmpty(playView)) {
                                String url = new SharedPreferencesServer(IApplication.context()).getRequestUrl(UrlInfo.ARTICLE_DETAIL);
                                url += "?rp=" + Constants.RP_PASSWORD + "&article_id=" + playView.getId();

                                new FinestWebView.Builder(this).theme(R.style.FinestWebViewTheme)
                                        .titleDefault("公告新闻")
                                        .showUrl(false)
                                        .statusBarColorRes(R.color.colorPrimaryDark)
                                        .toolbarColorRes(R.color.colorPrimary)
                                        .titleColorRes(R.color.white)
                                        .urlColorRes(R.color.colorPrimaryLight)
                                        .iconDefaultColorRes(R.color.finestWhite)
                                        .progressBarColorRes(R.color.finestWhite)
                                        .showSwipeRefreshLayout(true)
                                        .swipeRefreshColorRes(R.color.colorPrimaryDark)
                                        .menuSelector(R.drawable.selector_light_theme)
                                        .menuTextGravity(Gravity.CENTER)
                                        .menuTextPaddingRightRes(R.dimen.defaultMenuTextPaddingLeft)
                                        .dividerHeight(0)
                                        .gradientDivider(false)
                                        .setCustomAnimations(R.anim.slide_up, R.anim.hold, R.anim.hold, R.anim.slide_down)
                                        .showMenuShareVia(false)
                                        .stringResCopiedToClipboard(R.string.web_view_copied)
                                        .stringResCopyLink(R.string.web_view_copy)
                                        .stringResOpenWith(R.string.web_view_open)
                                        .show(url);

                            }
                            break;
                        case 1001:
                            NoticeInfoVo noticeInfoVo = new Gson().fromJson(receiverContentMode.getObj(), NoticeInfoVo.class);
                            if (!CommonUtil.objIsEmpty(noticeInfoVo)) {
                                Bundle bundle = new Bundle();
                                bundle.putString(BundleKey.NOTICE_ID, noticeInfoVo.getNoticeId());
                                bundle.putBoolean(BundleKey.HAS_READ, StringUtils.getBoolean(noticeInfoVo.getHasRead()));
                                UIHelper.showActivity(this, bundle, NoticeDetailActivity.class);
                            }
                            break;
                        case 1002:
                            VersionVo item = new Gson().fromJson(receiverContentMode.getObj(), VersionVo.class);
                            if (null != item) {
                                boolean isForce = item.isForce();
                                UpdateManager updateManager = new UpdateManager(item.getVersionRemark(), item.getDownloadUrl(), item.getVersionName(), Constants.APP_DOWNLOAD_FILE_NAME, isForce, this);
                                updateManager.checkUpdateInfo();
                            }
                            break;
                    }

                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

        }

    }


    @Subscribe
    public void onEventMainThread(UpDateUserInfoEvent upDateUserInfoEvent) {


        if (AppService.getInstance().isLogin()) {
            //更新个人信息
            LogUtils.LOGE("个人信息");
            httpUploadUserInfo();
        }
    }


    private void httpUploadUserInfo() {

        LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");

        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(this);
        String serverUrl = mSharedPreferencesServer.getRequestUrl(HttpPath.Login_user);

        HttpOkBase.httpBasePost(params,serverUrl, "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                if (httpClient) {
                    BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (HttpBack.httpBackError(baseMode)) {
                            UserInfoMode userInfoMode = JsonUtils.fromJson(mGson.toJson(baseMode.getResult()), UserInfoMode.class);

                            if (!CommonUtil.objIsEmpty(userInfoMode)) {
                                mSharedPreferencesHelper.setEmail(StringUtils.nullValue(userInfoMode.getEmail()));
                                mSharedPreferencesHelper.setUserPhotoUrl(StringUtils.nullValue(userInfoMode.getPhotoUrl()));
                                //通知侧边栏刷新个人信息
                                AppService.getBus().post(new DrawerRefreshEvent());
                                //通知个人中心
                                AppService.getBus().post(new UserSetRefreshEvent());

                            }
                        }
                    }
                } else {
                    ToastUtil.show("网络连接失败");
                }
            }
        });

    }


}
